	var FMP = chrome.extension.getBackgroundPage().FMP;
	
	var blockData = { 
			message: '<h1>Please wait...</h1>', 
			css: { border: '3px solid #a00', width: '50%', padding: 10 },
			overlayCSS: {cursor: null}
		};
	
	var stopUpdating = false;
	var stopUpdatingVolume = false;
	
	function filterPlaylist() {
		var val = $('#search').val();
		var list = $('#current_playlist').children();
		
		if(val == '' || $('#search')[0].defaultValue == val) {
			$('#current_playlist').prev().text('');
			list.removeClass('hide');
		} else {
			list.each(function() {
				if($(this).children('.title').text().toLowerCase().indexOf(val.toLowerCase()) == -1) {
					$(this).addClass('hide');
				} else {
					$(this).removeClass('hide');
				}
			});
			
			var found = list.filter(':visible').length;
			
			$('#current_playlist').prev().text('Found '+found+' songs matching "'+val+'" (total: '+list.length+')');
			
		}
	}
	
	function updateStatus() {
		var lastState = $('#userPanel').data('userID');
		
		var locked = true;
		
		if(FMP.mainStatus.get() && (lastState != FMP.data.userID) ) {
			$('#userPanel').data('userID', FMP.data.userID)
			$('body').unblock();
			locked = false;			
		}
		
		if(stopUpdating || ( $('.blockUI').length > 0 && locked)) {
			setTimeout(updateStatus, 100);
			return;
		}
		
		if(FMP.data.userID) {
			$('#loginForm').hide();
			
			if($('#logoutForm').find('.username').text() == '') {
				$('#logoutForm').find('.username').text(FMP.data.username)
			}
			$('#logoutForm').show();
		} else {
			$('#logoutForm').hide();
			$('#loginForm').show();
		}
	
		if(FMP.mainStatus.get() == null) {
			$('#loading').show();
			$('#main').hide();
		} else {
			$('#loading').hide();
			$('#main').show();
		}
		
		$('#video').button('option', 'disabled', FMP.status.videoID ? false : true);
		
		var tbl = $('#current_playlist');
		
		if(!tbl.data('playlist') || tbl.data('playlist') != FMP.playingNow.list) {
			var str = '';
			
			for(var i=0;i<FMP.playingNow.list.length;i++) {
				str += '<li class="ui-state-default" data-index="'+i+'"><div class="counter">*</div><div class="title">'+FMP.playingNow.list[i].artist+' - '+FMP.playingNow.list[i].title+'</div><div class="length">'+FMP.playingNow.list[i].length+'</div></li>';						
			}
			tbl.html(str);
			tbl.data('playlist', FMP.playingNow.list);
		}
		
		if(!tbl.data('inSorting')) {
			var idx = FMP.status.index;
			
			if(idx != null) {
				if(idx != -1) {
					if(tbl.children(':nth-child('+(idx+1)+')').length > 0 && !tbl.children(':nth-child('+(idx+1)+')').hasClass('current'))
					{
						tbl.children('.current').removeClass('current');
						tbl.children(':nth-child('+(idx+1)+')').addClass('current');
						
						var t = (tbl.parent().scrollTop() + tbl.children(':nth-child('+(idx+1)+')').position().top - (350/2)+18);
						
						if(FMP.playingNow.lastIndex != tbl.data('index')) {
							tbl.data('index', FMP.playingNow.lastIndex);
							$('#current_playlist').parent().scrollTop(t);
						}
					}
				}
			} else {
				tbl.find('.current').removeClass('current');
			}
		}
		
		tbl.sortable({
			placeholder: "ui-state-highlight",
			start: function() {
				$(this).data('inSorting', true);
			},
			stop: function() {
				//$(this).data('inSorting', false);
			},
			update: function(e, ui) {
				var that = $(this);
				var list = that.data('playlist');
				var newList = [];
				
				that.children().each(function(k,v) {
					newList.push(list[$(this).data('index')]);
					$(this).data('index', k);
				});
				
				that.data('playlist', newList);
				var newIndex = that.children().index(that.children('.current'));
				
				FMP.playingNow.add({replace: true, list: newList, force: false, newIndex: newIndex});
				
				that.data('index', newIndex);
				
				//that.children(':nth-child('+(newIndex+1)+')').addClass('current');
				
				setTimeout(function() {
					that.children(':nth-child('+(newIndex+1)+')').addClass('current');
				}, 100);
				
				setTimeout(function() {
					that.data('inSorting', false);
				}, 500);
			}
		}).disableSelection();
		
		
		//$('#status').html(JSON.stringify(FMP.status));
		
		var options, times = '', text = '';
		
		if(FMP.status.state == 'playing' || FMP.status.state == 'buffering' ) {
			options = {
				label: "pause",
				icons: {
					primary: "ui-icon-pause"
				}
			};
			text = FMP.status.title;
		} else {
			options = {
				label: "play",
				icons: {
					primary: "ui-icon-play"
				}
			};
			if(FMP.status.state != 'stopped') {
				text = '['+FMP.status.state+'] ' + FMP.status.title;
			}
		}
		
		if(FMP.status.state == undefined) {
			text = '';			
		} else if(FMP.status.state != 'stopped') {
			times = FMP.secondsToLength(FMP.status.position) + ' / ' + FMP.secondsToLength(FMP.status.duration);
		}
		
		$('#text div div').text(text);
		$('#times').text(times);
		
		if(!$('#play').data('label') || $('#play').data('label') != options.label) {
			$('#play').button( "option", options ).data('label', options.label);
		}
		
		var slider = $('#progressbar');
		
		
		if(FMP.status.position != undefined && FMP.status.duration != undefined && FMP.status.state != 'stopped') {
			if(slider.slider("option", "disabled")) {
				slider.slider("enable");
			}
			slider.slider('option', {value: Math.floor(FMP.status.position), 'max': Math.floor(FMP.status.duration)});
		} else {
			slider.slider('option', {'disabled': true, value: 0, max: 0});
		}
			
		if(!stopUpdatingVolume)
			$('#volumebar').slider('option', {value: FMP.data.options.get('volume')});
		
		setTimeout(updateStatus, 100);
	}
	
	$('#logout, #login, #signup').button();
	
	var treeItemPlayContext = function(e) {
		var el = $(e.srcElement || e.target).closest('li');
		if(el.length == 0) return;
		
		var tit = $.trim(el.find('.title').text());
		
		if(tit.length > 30) {
			tit = tit.slice(0,30)+'...';
		}
		
		$.vakata.context.show(
			el, {x: e.pageX+5, y: e.pageY+5},
			[
				{_class: "bold center vakata-title ", label: tit, action: false, separator_after: true, hideIcons: true},
				{icon: "images/video.png",  label: "Play now", action: function(a) { $(a.reference).trigger('dblclick'); }},
				{icon: "images/video.png",  label: "Delete from this playlist", action: function(a) { 
					var idx = $(a.reference).data('index');
					
					var li = $(a.reference);
					
					var isCurrent = li.hasClass('current');
					
					li.remove();
					
					var that = $('#current_playlist');
					var list = that.data('playlist');
					
					list.splice(idx, 1);
					
					that.data('playlist', list);
					
					var send = {replace: true, list: list, force: false};
					var stop = false, next = false;
					if(isCurrent) {
					
						if(FMP.data.options.get('shuffle')) {
							next = true;
						} else {
							stop = true;
						}
					} else {
						var newIndex = that.children().index(that.children('.current'));
						send.newIndex = newIndex;
					}
					
					FMP.playingNow.add(send);
					
					if(stop) {
						FMP.postToFrame({action: 'stop'});
					}
					if(next) {
						FMP.postToFrame({action: 'next'});
					}
				}},
				{icon: "images/video.png",  label: "Copy video url", action: function(a) { 
					var idx = $(a.reference).data('index');
					var item = $('#current_playlist').data('playlist')[idx];
					
					if(item) {
						var url = FMP.getVideoUrl(item.source, item.videoID);
						FMP.copyToClipboard(url);
					}
				}},
			]);
		return false;
	};
	
	$('#current_playlist').delegate('li', "contextmenu", treeItemPlayContext);
	
	$(document).delegate('#logout', 'click', function() {
		$('body').block(blockData);
		FMP.logout();
		chrome.extension.getBackgroundPage().localStorage.removeItem('token');
		FMP.loadNewUser(null, null, null);
		window.close();		
		return false;
	});
	
	$('#login').click(function() { FMP.tab.open('login'); window.close(); });
	$('#signup').click(function() { FMP.tab.open('register'); window.close(); });

	$('#text span').marquee('marquee')
	.mouseover(function () {
		$(this).trigger('stop');
	}).mouseout(function () {
		$(this).trigger('start');
	}).mousemove(function (event) {
		if ($(this).data('drag') == true) {
			this.scrollLeft = $(this).data('scrollX') + ($(this).data('x') - event.clientX);
		}
	}).mousedown(function (event) {
		$(this).data('drag', true).data('x', event.clientX).data('scrollX', this.scrollLeft);
	}).mouseup(function () {
		$(this).data('drag', false);
	});

	$( "#prev" ).button({
		text: false,
		icons: {
			primary: "ui-icon-seek-prev"
		}
	}).click(function() {
		FMP.postToFrame({action: 'prev'});
	});
	
	$( "#play" ).button({text: false})
	.click(function() {
		if ( $( this ).text() === "pause" ) {
			FMP.postToFrame({action: 'pause'});
		} else if( FMP.playingNow.list.length != 0 ) {
			if(FMP.status.state == 'paused') {
				FMP.postToFrame({action: 'pause'});
			} else {
				FMP.postToFrame({action: 'playNow', force: true});
			}
		}
	});
	
	var switchPlaylist = function(el) {
		var options;
		
		if( el.prop('checked') ) {
			options = {
				//label: "play",
				icons: {
					primary: "ui-icon-folder-open"
				}
			};
			$('#current_playlist_wrapper').show();
		} else {
			options = {
				//label: "play",
				icons: {
					primary: "ui-icon-folder-collapsed"
				}
			};
			$('#current_playlist_wrapper').hide();
			$('html').height($('html').height()-$('#current_playlist_wrapper').height());
			$('body').height($('body').height()-$('#current_playlist_wrapper').height());
		}
		el.button( "option", options );
	};
	
	$( "#playlist" ).prop('checked', FMP.data.options.get('showPlaylistInPlayer'));
	$( "#playlist" ).button({text: false, create: function(event, ui) {
		switchPlaylist($(this));
	}})
	.click(function() {
		FMP.data.options.set('showPlaylistInPlayer', $(this).prop('checked'));
		switchPlaylist($(this));
	});
	
	var switchVolume = function(el) {
		var options;
		
		var vol = FMP.data.options.get('volume');
		
		if( vol == 0 ) {
			options = {
				label: "Mute off",
				icons: {
					primary: "ui-icon-volume-off"
				}
			};
		} else {
			options = {
				label: "Mute",
				icons: {
					primary: "ui-icon-volume-on"
				}
			};
		}
		el.button( "option", options );
	};
	
	
	
	$( "#volume" ).button({text: false, create: function(event, ui) {
		switchVolume($(this));
	}})
	.click(function() {
		if($(this).children().hasClass('ui-icon-volume-off')) {
			FMP.data.options.set('volume', FMP.data.options.get('lastVolume'));
		} else {
			FMP.data.options.set('lastVolume', FMP.data.options.get('volume'));
			FMP.data.options.set('volume', 0);
		}
		switchVolume($(this));
	});
	
	$( "#stop" ).button({
		text: false,
		icons: {
			primary: "ui-icon-stop"
		}
	})
	.click(function() {
		FMP.postToFrame({action: 'stop'});
	});
	
	$( "#next" ).button({
		text: false,
		icons: {
			primary: "ui-icon-seek-next"
		}
	}).click(function() {
		FMP.postToFrame({action: 'next'});
	});
	
	$( "#shuffle" ).prop('checked', FMP.data.options.get('shuffle')).button({text: false, icons: {primary: "ui-icon-shuffle"}}).click(function() {
		FMP.data.options.set('shuffle', $(this).prop('checked'));
	});

	$('#current_playlist').delegate('li', 'dblclick', function() {
		var idx = $(this).prevAll().length;
		FMP.postToFrame({action: "playIndex", index: idx});
	});
	
	$( "#repeat" ).prop('checked', FMP.data.options.get('repeat')).button({text: false, icons: {primary: "ui-icon-refresh"}}).click(function() {
		FMP.data.options.set('repeat', $(this).prop('checked'));
	});
	
	$( "#video" ).button({text: false, icons: {primary: "ui-icon-video"}}).click(function() {
		if(FMP.status.videoID) {
			FMP.postToFrame({action: 'pause'});
			var url = FMP.getVideoUrl(FMP.status.source, FMP.status.videoID);
			
			chrome.tabs.create({url: url});
		}
	});
	
	$('#library').button({text: false, icons: {primary: "ui-icon-note"}}).click(function() {
		FMP.tab.open('library');
	});
	
	$('#trash').button({text: false, icons: {primary: "ui-icon-trash"}}).click(function() {
		FMP.playingNow.add({replace: true, list: [], force: true});
	});
	
	$('#save').button({text: false, icons: {primary: "ui-icon-disk"}}).click(function() {
		var name = prompt('Enter new playlist name');
		
		if(name == null) return;

		if(name == '') {
			alert("Name must be set.");
		} else {
			var queries = [];
			
			var song_ids = jQuery.map($('#current_playlist').data('playlist'), function(item) {
				return item.id;
			});
			
			queries.push( {query: FMP.squel.insert().into('playlists').set('name', name).set('userID', FMP.data.userID), 
				callbackOpt: song_ids,
				callback: function(a) {
					if(a.newId) {
						var idx = FMP.data.add('playlists', {id: a.newId, name: name});
						FMP.data['addSong']('playlists', a.newId, a.params, true);
						FMP.tab.send('library', 'addItemToPlaylistTree', {id: a.newId, name: name, idx: idx} );
					}
				}
			});
			
			FMP.database.query(queries);
		}
	});
	
	$('#search').focus(function() {
        if(this.value == this.defaultValue) {
            this.value = '';
			$(this).css('color', '#333');
        }
    }).blur(function() {
        if(this.value == '') {
            this.value = this.defaultValue;
			$(this).css('color', '#666');
        }
    }).bind('propertyChange input', function() {
		var that = $(this);
		clearTimeout(that.data('timeout'));
		that.data('timeout', setTimeout(filterPlaylist, 250));
	});
	
	$( "#progressbar" ).slider({
		"range": "min",
		'min': 0,
		max: Math.floor(FMP.status.duration),
		'step': 1,
		value: Math.floor(FMP.status.position),
		start: function() {
			stopUpdating=true;
		},
		slide: function(e, ui) 
		{
			$(this).data('next', ui.value);
			var times = FMP.secondsToLength(ui.value) + ' / ' + FMP.secondsToLength(FMP.status.duration);
			$('#times').text(times);
		},
		stop: function(e, ui) 
		{
			var seek = $(this).data('next');
			var that = this;
			
			$('#debug').html(seek);
			
			FMP.postToFrame({action: 'seek', data: seek});
			setTimeout(function() { stopUpdating=false; }, 1000);
		}
	});
	
	$(document).bind('click', function(e) {
		var el = $(e.srcElement || e.target);
		if(el.closest('.ui-autocomplete').length > 0)
			return;
		else if ( $('#playlist_select').autocomplete("widget").is(":visible")) {
			$('#playlist_select').autocomplete("close");
			return;
		}
	});
	
	$("#playlist_select").autocomplete({
		position: { my : "left bottom", at: "left top", of: "#load" },
		minLength: 0,
		delay: 0,
		select: function(e,res) {
			FMP.database.loadPlaylist(res.item.value);
		}
	});
	
	$('#load').button({text: false, icons: {primary: "ui-icon-folder-open"}}).click(function(){
		var input = $('#playlist_select');
		var inputID = input.attr('id');
		
		var widget = input.autocomplete("widget");
		widget.position({left: 0, top: 300});
		
		if (input.autocomplete("widget").is(":visible")) {
			input.autocomplete("close");
			return false;
		}
		
		var playlists = $.map(FMP.data.getSorted('playlists'), function(item) {
			return {label: item.attr.title, value: item.attr["data-playlist-id"]};
		});
		
		input.autocomplete({
			source: playlists
		});
		
		input.autocomplete("search", "");
		//input.focus();
		return false;
	});
	
	$('#volumebar').slider({
		"range": "min",
		min: 0,
		max: 100,
		step: 1,
		value: Math.floor(FMP.data.options.get('volume')),
		start: function() {
			stopUpdatingVolume=true;
		},
		slide: function(e, ui) 
		{
			$(this).data('next', ui.value);
		},
		stop: function()
		{
			var vol = $(this).data('next');
			var that = this;
			
			//$('#debug').html(vol);
			FMP.data.options.set('volume', vol);
			
			switchVolume($('#volume'));
			
			setTimeout(function() { stopUpdatingVolume=false; }, 1000);
		}
	});
	
	updateStatus();